//
//  FPBaseProtocolView.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/5/14.
//

#import "FPBaseProtocolView.h"
#import "FPProtocolPopupView.h"

@interface FPBaseProtocolView () <TTTAttributedLabelDelegate>

@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *containerView;

@end

@implementation FPBaseProtocolView

+ (instancetype)sharedInstance {
    
    static FPBaseProtocolView *instance;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        instance = [[FPBaseProtocolView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    });
    
    return instance;
}

+ (void)showWithText:(NSArray *)protocolSource onAction:(void (^)(NSUInteger))actionBlock protocolDidSelectAction:(nonnull void (^)(FPProtocolModel * _Nonnull))protocolDidSelectAction {
    
    FPBaseProtocolView *view = [FPBaseProtocolView sharedInstance];

    if (!view.superview) {
        
        UIWindow *keyWindow = [UIApplication sharedApplication].windows.firstObject;
        [keyWindow addSubview:view];
        [view setupUIWithText:protocolSource action:actionBlock protocolDidSelectAction:protocolDidSelectAction];
    }
}

+ (void)hide {
    
    FPBaseProtocolView *view = [FPBaseProtocolView sharedInstance];

        [UIView animateWithDuration:0.2 animations:^{
           
            view.containerView.transform = CGAffineTransformMakeScale(0.01, 0.01);
            view.alpha = 0;
            
        } completion:^(BOOL finished) {
           
            // 清理子视图
            [view.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

            // 恢复 transform，防止下次动画失败
            view.containerView.transform = CGAffineTransformIdentity;

            // 防止残留状态影响下一次
            [view.backgroundView removeFromSuperview];
            [view.containerView removeFromSuperview];
            view.backgroundView = nil;
            view.containerView = nil;

            // 最后移除自身
            [view removeFromSuperview];
        }];
}

- (void)setupUIWithText:(NSArray *)protocolSource action:(void (^)(NSUInteger))actionBlock protocolDidSelectAction:(void (^)(FPProtocolModel *model))protocolDidSelectAction {
   
    self.alpha = 1.0;

    if (!self.backgroundView) {
        
        self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
        self.backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [self addSubview:self.backgroundView];

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped)];
        [self.backgroundView addGestureRecognizer:tap];
    }

    if (!self.containerView) {
        
        self.containerView = [[UIView alloc] init];
        self.containerView.backgroundColor = [UIColor clearColor];
        [self addSubview:self.containerView];
    }

    FPProtocolPopupView *content = [[[NSBundle mainBundle] loadNibNamed:@"FPProtocolPopupView" owner:nil options:nil] firstObject];
    
    NSMutableString *protocolStr = NSMutableString.string;
    
    for (FPProtocolModel *model in protocolSource) {
        
        [protocolStr appendFormat:@"%@",model.agreementName];
    }
    
    NSString *text = [NSString stringWithFormat:@"感谢您使用众鑫花，请仔细阅读%@。当您点击同意并开始使用该服务时，即表示您已理解并同意该条款内容。",protocolStr];
    
    CGFloat height = [UIView heightWithString:text labelWidth:SCREEN_WIDTH - 32.f - 64.f fontSize:14.f];
    
    content.frame = CGRectMake(0, 0, SCREEN_WIDTH - 64.f, height + 44.f + 60.f);
//    content.contentLab.text = text;
    content.btn1.tag = 1001;
    content.btn2.tag = 1002;

    [content setProtocol:protocolSource];
    
    content.actionHandler = ^(NSUInteger index) {
     
        if (actionBlock) {
            
            [FPBaseProtocolView hide];
            actionBlock(index);
        }
    };
    
    content.protocolDidSelectAction = ^(FPProtocolModel * _Nonnull model) {
      
        if (protocolDidSelectAction) {
            
            [FPBaseProtocolView hide];
            protocolDidSelectAction(model);
        }
    };
    
    [self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.containerView addSubview:content];

    content.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
    
        [content.topAnchor constraintEqualToAnchor:self.containerView.topAnchor],
        [content.bottomAnchor constraintEqualToAnchor:self.containerView.bottomAnchor],
        [content.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor],
        [content.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor],
    ]];

    self.containerView.frame = content.frame;
    self.containerView.center = self.center;
    self.containerView.transform = CGAffineTransformMakeScale(0.01, 0.01);

    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.3 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        self.containerView.transform = CGAffineTransformIdentity;
        
    } completion:nil];
}

- (void)backgroundTapped {
    
    [FPBaseProtocolView hide];
}




@end
